import { ref, onMounted, reactive, toRefs } from 'vue'
import Child from './child.js'
export default {
    setup() {
        const childRef = ref(null)
        const state = reactive({
            userList: [],
            userIds: [1, 2, 3],
            userMap: new Map(),
        })
        const toggle = () => {
            state.userIds = childRef.value.filter(e => {
                return e.isShowName
            }).map(e => e.item.id)
            getUserName()
        }

        const getUserName = () => {
            fetch('/api/user', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ userIds: state.userIds }),
            }).then(res => res.json()).then(data => {
                state.userList = data
                state.userIds.forEach(id => {
                    state.userMap.set(id, data.find(item => item.id === id))
                })
            })
        }

        onMounted(() => {
            getUserName()
        })

        return { childRef, ...toRefs(state), toggle }
    },
    components: {
        Child
    },

    template: `
        <div class="app-container">
            <h1>admin</h1>
            <Child ref="childRef" v-for="item , index in userList" :key="item.id" @toggle="toggle" :item="item"></Child>
        </div>
        `,
}